<?php
namespace WDB\Wrapper;
use WDB,
    WDB\Exception;

/**
 * Static class for creating iTable objects.
 *
 * @author Richard Ejem <richard(at)ejem.cz>
 * @package WDB
 */
class TableFactory
{
    /**
     * Creates table wrapper from table analyzer.
     *
     * @param WDB\Analyzer\Table $table
     * @return iTable
     */
    public static function fromAnalyzer(WDB\Analyzer\iTable $table)
    {
        $tClass = $table->getWrapperClass();
        if ($tClass === NULL)
        {
            $tClass = '\\WDB\\Wrapper\\Table';
        }
        else
        {
            $tClass = WDB\Utils\System::findClass($tClass, WDB\Config::read('userWrappersClassPrefix'));            
        }
        return new $tClass($table);
    }    
    
    /**
     * Creates table wrapper from table name in database.
     *
     * @param string table name
     * @param string|null schema name
     * @param WDB\Database|null source database
     * @return iTable 
     * 
     * @throws Exception\NotFound
     */
    public static function fromName($table, $schema = NULL, WDB\Database $database = NULL)
    {
        if ($database === NULL)
        {
            $database = WDB\Database::getDefault();
        }
        if ($schema === NULL)
        {
            $schema = $database->getSchema();
        }
        else
        {
            $schema = $database->getSchema($schema);
        }
        if (!isset($schema->tables[$table]))
        {
            throw new Exception\NotFound("Table $table not found.");
        }
        $analyzer = $schema->tables[$table];
        
        return self::fromAnalyzer($analyzer);
    }
    
    /**
     * Creates table wrapper from table locator (table name, table schema and a named database connection).
     *
     * @param WDB\Structure\TableLocator
     * @return iTable
     */
    public static function fromLocator(WDB\Structure\TableLocator $locator)
    {
        return self::fromName($locator->table, $locator->schema, WDB\Database::getInstance($locator->connection));
    }
}
